#!/usr/bin/python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
import urllib
import re
import datetime
import os

def getYesterday():
    today = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    yesterday = today-oneday
    return str(yesterday)

def write2db(filename,entry):
    hdb = open(filename,'a')
    hdb.write(entry.encode('utf-8'))
    hdb.close()

def getEntryStr(key,valuelist):
    '''
    return the entry string, TODO: unicode convert to string?
    '''
    #print key
    #print valuelist
    retstr = "" + key
    for i in valuelist:
        retstr = retstr + "\t" + i
    #print retstr
    return retstr+ "\n"

def writeHeader2db(filename,header):
    if(os.path.isfile(filename)):
        return
    else:
        #print header
        write2db(filename,header)
        return

def getTargetbuild(url,keyword):
   
    html_src = urllib.urlopen(url).read()
    mysoup = BeautifulSoup(html_src)
    unstablelist = []
    #print keyword

    for item in mysoup.findAll("img",alt=re.compile('^Unstable.+')):
        target=item.parent.parent.parent.findNextSibling().find('font',color = "green")
        if(target):
                tmp = str(target.string)
                if tmp.__contains__(keyword):
                    unstablelist.append(tmp)
    #print unstablelist

    failedlist = []
    for item in mysoup.findAll("img",alt=re.compile('^Failed.+')):
        target=item.parent.parent.parent.findNextSibling().find('font',color = "red")
        if(target):
                tmp = str(target.string)
                if tmp.__contains__(keyword):
                    failedlist.append(tmp)
    #print failedlist

    successlist = []
    for item in mysoup.findAll("img",alt=re.compile('^Success.+')):
        target=item.parent.parent.parent.findNextSibling().find('font',color = "green")
        if(target):
                tmp = str(target.string)
                if tmp.__contains__(keyword):
                    successlist.append(tmp)
    #print successlist

    return [unstablelist,successlist,failedlist]

def main():
    fb1108_url = "http://hzlinv23.china.nsn-net.net:8080/view/CI/view/CI_Builds/job/LTE_eNB_FSM3_TDD_FB1108/"
    trunk_url = "http://hzlinv23.china.nsn-net.net:8080/view/CI/view/CI_Builds/job/LTE_eNB_FSM3_TDD_trunk/"

    filename= '/home/zhenghwa/analysis_dir/cibuild.db'
    tFB1108 = 'FB1108'
    tTRUNK = 'TRUNK'
    tDate = 'DATE'
    yesterday =  getYesterday().split("-")
    fb1108_keyword ='LNT2.0_ENB_1108'+ yesterday[1]+yesterday[2]
    trunk_keyword = 'LNT0.0_ENB_' + yesterday[0] + yesterday[1] + yesterday[2]
    a =  getTargetbuild(fb1108_url,fb1108_keyword)
    b =  getTargetbuild(trunk_url,trunk_keyword)

    entry = getYesterday() + '\t' + str(len(a[0]) + len(a[1]))  + '\t' + str(len(b[0]) + len(b[1])) + '\n'

    #print entry
    tHeaderList = [tFB1108, tTRUNK]

    ccc = getEntryStr(tDate,tHeaderList)
    writeHeader2db(filename,ccc);
    write2db(filename,entry)

if __name__ == '__main__':
    main()


